package threadDemo;

/**
 * 模拟取钱问题，线程安全
 */
public class Test16 {
    public static void main(String[] args) {
        Account account = new Account();
        account.setMoney(100);
        WithdrawMoneyimplements w = new WithdrawMoneyimplements(account,50,"小明");
        WithdrawMoneyimplements w1 = new WithdrawMoneyimplements(account,100,"小明对象");
        w.start();
        w1.start();
    }
}

class Account {
    private String name;
    private int money;

    public Account(String name, int money) {
        this.name = name;
        this.money = money;
    }

    public Account() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
}
class WithdrawMoneyimplements extends Thread {
    /**
     * 账户
     */
    private Account account;
    /**
     * 取得钱数
     */
    private int money;

    public WithdrawMoneyimplements(Account account, int money,String name) {
        super(name);
        this.account = account;
        this.money = money;
    }

    @Override
    public void run() {
        synchronized (account){
            if(account.getMoney()-money<0){
                System.out.println(Thread.currentThread().getName()+" "+"钱不够了，取不了了");
                return;
            }
            //模拟延迟
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.getName()+"拿了："+money);
            // 卡内余额
            account.setMoney(account.getMoney()-money);
            System.out.println("卡内余额："+account.getMoney());
        }
    }



}
